<?php

/**
 * 百大订单交易上传服务
 */
namespace App\Service\OrderService;
use App\Service\BaseService;
use App\Service\OrderService\OrderInterfaceService\OrderTradeBdCrmCenter;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplierAmountExtra;
use App\Model\CommodityModel\CommodityArchives;
use App\Service\AppService\SystemCacheConfigService;
use App\Model\PssModel\OrderRefund;
use App\Model\PssModel\OrderSupplier;
use App\Service\OrderService\OrderRefundService\OrderRefundMessage;
use App\Service\OrderService\OrderInterfaceService\OrderPay;
use App\Service\OrderService\OrderInterfaceService\OrderPreSellService;

class OrderBdCrmTradeService extends BaseService
{
    /**
     * 上传百大交易订单明细
     * 下单支付
     * @param array $binfo
     * @param array $order
     * @param array $supplierOrder
     * @param array $orderGoods
     * @param array $update_amount_extra
     */
    public function uploadBdCrmOrderPay(array $binfo,array $order,array $supplierOrder,array $orderGoods,array $update_amount_extra)
    {
        $isNewMode = getIsNewBbcJavaMode();
        if( $isNewMode == 0 ) {
            return Normal::returnCode(Normal::SUC, "当前业务类型无须处理");
        }
        
        if( $binfo['is_full_support_after_sale'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"当前渠道数据类型无须处理");
        }
        
        if( $binfo['is_support_crm_upload'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"当前渠道数据类型无须处理");
        }
        
        if( empty($order['payTypeCode']) ) {//此处是尾款和正常支付payCode
            return Normal::returnCode(Normal::FAIL,"当前crm支付编码payTypeCode不能为空");
        }
        
        //原始订单数据ID
        $order_supplier_id  = $supplierOrder['id'];
        $order_trade_type   = $supplierOrder['order_trade_type'];
        
        //判断是否预售订单
        $is_same_pay_mode = false;
        $deposit_pay_way  = '';
        $payMode = $order['payMode'];
        if( $order_trade_type == OrderSupplier::order_trade_type_deposit && $payMode != OrderPay::PAY_MODE_NORMAL )
        {
            if( isset($update_amount_extra['deposit_mode']) && $update_amount_extra['deposit_mode'] == 2  ) 
            {
                return Normal::returnCode(Normal::SUC,"仅支付定金的情况下，不需要推送CRM接口");
            }
            
            $_extra_money = OrderSupplierAmountExtra::instance()->info(['order_id'=>$order_supplier_id]);
            if( empty($_extra_money['deposit_pay_way']) ) {
                return Normal::returnCode(Normal::FAIL,"定金支付数据异常!");
            }
            $deposit_pay_way = $_extra_money['deposit_pay_way'];
            
            //判断定金和尾款支付方式是否一致
            if( $_extra_money['deposit_pay_way'] == $update_amount_extra['final_pay_way'] ) {
                $is_same_pay_mode = true;
            }
        }
        
        //获取bd crm 交易中心config
        $config = OrderTradeBdCrmCenter::instance()->getBdCrmConfig();
        $client = new OrderTradeBdCrmCenter();
        
        
        //**************************上传交易商品接口****************************************
        
        //查询主商品档案三方skucode数据
        $skuCodes = array_column($orderGoods,'skucode');
        $list = CommodityArchives::instance()->select(['SKUCode','SkuExtraCode'])->whereIn('SKUCode',$skuCodes)->get()->toArray();
        $listMap = array_column($list,null,'SKUCode');
        $crmArticleList = [];
        //结账的总金额
        $amount_total = $precard_money_total = $point_money_total = $qedk_money_total = $real_pay_money = $deposit_money_total = '0.00';
        foreach ($orderGoods as $index => $item) 
        {
            $skucode                        = $item['skucode'];
            $skucode                        = !empty($listMap[$skucode]) && !empty($listMap[$skucode]['SkuExtraCode']) ? $listMap[$skucode]['SkuExtraCode'] : $skucode;
            $quantity                       = $item['quantity'];
            $price                          = $item['price'];
            $discount_red_envelope_money    = $item['discount_red_envelope_money'];
            $discount_activity_money        = $item['discount_activity_money'];
            $discount_coupon_money          = $item['discount_coupon_money'];
            $discount_payway_money          = $item['discount_payway_money'];
            $discount_precard_money         = $item['discount_precard_money'];
            $discount_point_money           = $item['discount_point_money'];
            $discount_money                 = $item['discount_money'];
            
            //定金分摊优惠部分
            $discount_deposit_goods_money       = $item['discount_deposit_goods_money'];
            $discount_deposit_delivery_money    = $item['discount_deposit_delivery_money'];
            $discount_deposit_money             = bcadd($discount_deposit_goods_money,$discount_deposit_delivery_money,2);
            
            //实际商品交易 = 实际支付 + 预付卡 + 积分
            $single_total_price             = bcmul((string)$quantity, (string)$price,2);
            $single_real_total_money        = bcsub((string)$single_total_price, (string)$discount_money,2);
            
            //实际优惠金额 = 单价 - 预付卡 + 积分
            $discountAmount                 = bcsub((string)$discount_money, (string)$discount_precard_money,2);
            $discountAmount                 = bcsub((string)$discountAmount, (string)$discount_point_money,2);
            $discountAmount                 = bcsub((string)$discountAmount, (string)$discount_deposit_money,2);
            
            //交易总金额(商品分摊实际支付金额+预付卡金额+积分抵扣金额+定金优惠金额)
            $amount                         = bcadd($single_real_total_money, $discount_point_money,2);
            $amount                         = bcadd($amount, $discount_precard_money,2);
            $amount                         = bcadd($amount, $discount_deposit_money,2);
            
            //如果实际交易订单amount 为0，要设置为完全抵扣
            if( $amount <= 0 ) {
                $amount                 = $discountAmount;
                $discountAmount         = '0.00';
                $qedk_money_total       = bcadd((string)$qedk_money_total,(string)$amount,2);
                $real_pay_money         = bcadd((string)$real_pay_money,(string)$discountAmount,2);
            }
            else
            {
                $real_pay_money         = bcadd((string)$real_pay_money,(string)$single_real_total_money,2);
            }
            
            $crmArticleList[] = [
                'inx'               => $index,
                'originalInx'       => -1,
                'code'              => $skucode,
                'saleDept'          => $config['saleDept'],
                'quantity'          => $quantity,
                'amount'            => $amount,
                'discountAmount'    => $discountAmount,
                'ContractCode'      => $config['contractNo'],
                'noCent'            => 'N'
            ];
            $amount_total          = bcadd((string)$amount_total,(string)$amount,2);
            $precard_money_total   = bcadd((string)$precard_money_total,(string)$discount_precard_money,2);
            $point_money_total     = bcadd((string)$point_money_total,(string)$discount_point_money,2);
            $deposit_money_total   = bcadd((string)$deposit_money_total,(string)$discount_deposit_money,2);
        }
        
        //如果有运费的情况下单独在追加一个运费商品
        $deliver_money = $supplierOrder['deliver_money'];
        $real_pay_money = bcadd((string)$real_pay_money,(string)$deliver_money,2);
        if( $deliver_money > 0 ) 
        {
            $crmArticleList[] = [
                'inx'               => count($orderGoods),
                'originalInx'       => -1,
                'code'              => $config['crm_trade_freight_goods_sku'],
                'saleDept'          => $config['saleDept'],
                'quantity'          => 1,
                'amount'            => $deliver_money,
                'discountAmount'    => '0.00',
                'ContractCode'      => $config['contractNo'],
                'noCent'            => 'Y'
            ];
        }
        
        $createOrderParam  = [
            'requestData'   => [
                'vipId'             => $order['vipId'],
                'billId'            => 0,
                'orderNo'           => $order['orderSn'],
                'type'              => $order['type'],
                'orderCreateTime'   => !empty($order['payTime']) ? date("Y-m-d H:i:s",$order['payTime']) : date("Y-m-d H:i:s"),
                'articleList'       => $crmArticleList
            ]
        ];
        
        OrderSupplierAmountExtra::instance()->where('order_id',$order_supplier_id)->update(['order_pay_request'=>json_encode($order)]);
        $order_amount_extra = OrderSupplierAmountExtra::instance()->info([
            'order_id'  => $order_supplier_id
        ]);
        if( empty($order_amount_extra)) {
            return Normal::returnCode(Normal::FAIL,"订单数据附加属性不存在，请核对!");
        }
        
        //解析报文
        $order_crm_contents_arr = !empty($order_amount_extra['order_crm_contents']) ? json_decode($order_amount_extra['order_crm_contents'],true) : [];
        if( empty($order_crm_contents_arr['serverBillid']) )
        {
            $result = $client->vipUserOrderTradeCreate($createOrderParam);
            if( $result['code'] != Normal::SUC ) {
                return $result;
            }
            
            $response = $result['data'];
            if( empty($response['serverBillid']) ) {
                return Normal::returnCode(Normal::FAIL,"CRM未成功返回消费记录serverBillid，请核验!");
            }
            
            
            $response['bd_crm_amount']         = $real_pay_money;
            $response['bd_crm_precard_money']  = $precard_money_total;
            $response['bd_crm_point_money']    = $point_money_total;
            $response['bd_crm_qedk_money']     = $qedk_money_total;
            $response['bd_crm_article_list']   = $crmArticleList;
            
            //更新数据表
            OrderSupplierAmountExtra::instance()->where('order_id',$order_supplier_id)->update([
                'order_crm_create'      => json_encode($createOrderParam,JSON_UNESCAPED_UNICODE),
                'order_crm_contents'    => json_encode($response,JSON_UNESCAPED_UNICODE)
            ]);
            
            $serverBillId = $response['serverBillid'];
            $order_crm_contents_arr = $response;
        }
        else
        {
            $serverBillId          = $order_crm_contents_arr['serverBillid'];
            $real_pay_money        = $order_crm_contents_arr['bd_crm_amount'];
            $precard_money_total   = $order_crm_contents_arr['bd_crm_precard_money'];
            $point_money_total     = $order_crm_contents_arr['bd_crm_point_money'];
            $qedk_money_total      = $order_crm_contents_arr['bd_crm_qedk_money'];
        }
        
        //*********************************************准备结账***********************************************************
        if( empty($order_crm_contents_arr['serverBillIdPrePay']) ) {
            
            //实际支付金额
            $paymentList = [];
            
            //如果支付方式相同的情况下，需要合并支付金额
            if( $is_same_pay_mode ) 
            {
                $_same_pay_money = bcadd($real_pay_money,$deposit_money_total,2);
                if( !empty($_same_pay_money) && bccomp($_same_pay_money,'0.00',2) > 0)
                {
                    $oneline_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$order['payTypeCode']);
                    if( empty($oneline_pay_config) ) {
                        return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                    }
                
                    if( empty($oneline_pay_config['代码']) ) {
                        return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                    }
                
                    $paymentList[] = [
                        'PayTypeCode'   => $oneline_pay_config['代码'],
                        'PayMoney'      => $_same_pay_money,
                        'IsCashCard'    => '0',
                        'BJ_TQ'         => '0'
                    ];
                }
            } 
            else
            {
                //上传正在支付金额
                if( !empty($real_pay_money) && bccomp($real_pay_money,'0.00',2) > 0)
                {
                    $oneline_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$order['payTypeCode']);
                    if( empty($oneline_pay_config) ) {
                        return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                    }
                
                    if( empty($oneline_pay_config['代码']) ) {
                        return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                    }
                
                    $paymentList[] = [
                        'PayTypeCode'   => $oneline_pay_config['代码'],
                        'PayMoney'      => $real_pay_money,
                        'IsCashCard'    => '0',
                        'BJ_TQ'         => '0'
                    ];
                }
                
                //存在第二种支付方式交易金额
                if( !empty($deposit_money_total) && bccomp($deposit_money_total,'0.00',2) > 0)
                {
                    $oneline_deposit_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$deposit_pay_way);
                    if( empty($oneline_deposit_pay_config) ) {
                        return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                    }
                
                    if( empty($oneline_deposit_pay_config['代码']) ) {
                        return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                    }
                
                    $paymentList[] = [
                        'PayTypeCode'   => $oneline_deposit_pay_config['代码'],
                        'PayMoney'      => $deposit_money_total,
                        'IsCashCard'    => '0',
                        'BJ_TQ'         => '0'
                    ];
                }
            }
            
            
            //全额抵扣金额
            if( !empty($qedk_money_total) && bccomp($qedk_money_total,'0.00',2) > 0) 
            {
                $qedk_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_qedk_pay');
                if( empty($qedk_pay_config) ) {
                    return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                }
                
                if( empty($qedk_pay_config['代码']) ) {
                    return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                }
                
                $paymentList[] = [
                    'PayTypeCode'   => $qedk_pay_config['代码'],
                    'PayMoney'      => $qedk_money_total,
                    'IsCashCard'    => '0',
                    'BJ_TQ'         => '0'
                ];
            }
            
            //预付卡
            if( !empty($precard_money_total) && bccomp($precard_money_total,'0.00',2) > 0)
            {
                $precard_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_precard_pay');
                if( empty($precard_pay_config) ) {
                    return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                }
                
                if( empty($precard_pay_config['代码']) ) {
                    return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-预付卡对应百大CRM参数代码未配置成功，不能为空!");
                }
            
                $paymentList[] = [
                    'PayTypeCode'   => $precard_pay_config['代码'],
                    'PayMoney'      => $precard_money_total,
                    'IsCashCard'    => '1',
                    'BJ_TQ'         => '0'
                ];
            }
            
            //积分
            if( !empty($point_money_total) && bccomp($point_money_total,'0.00',2) > 0)
            {
                $points_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_point_pay');
                if( empty($points_pay_config) ) {
                    return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                }
                
                if( empty($points_pay_config['代码']) ) {
                    return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-积分对应百大CRM参数代码未配置成功，不能为空!");
                }
                
                $paymentList[] = [
                    'PayTypeCode'   => $points_pay_config['代码'],
                    'PayMoney'      => $point_money_total,
                    'IsCashCard'    => '0',
                    'BJ_TQ'         => '0'
                ];
            }
            
            $prepare_pay_param =
            [
                'requestData'   => [
                    'serverBillId'  => $serverBillId,
                    'paymentList'   => $paymentList
                ]
            ];
            $result_prepare_pay = $client->vipUserOrderTradePreparePay($prepare_pay_param);
            if( $result_prepare_pay['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"交易订单准备结账失败[{$result_prepare_pay['msg']}]，请核验!");
            }
            
            $order_crm_contents_arr['serverBillIdPrePay']       = true;
            $order_crm_contents_arr['OnlinePayTypeCode']        = $oneline_pay_config['代码'] ?? '';
            $order_crm_contents_arr['OnlinePayTypeDepositCode'] = $oneline_deposit_pay_config['代码'] ?? '';
            $order_crm_contents_arr['PreCardPayTypeCode']       = $precard_pay_config['代码'] ?? '';
            $order_crm_contents_arr['PointsPayTypeCode']        = $points_pay_config['代码'] ?? '';
            $order_crm_contents_arr['QedkPayTypeCode']          = $qedk_pay_config['代码'] ?? '';
            
            //更新数据表
            OrderSupplierAmountExtra::instance()->where('order_id',$order_supplier_id)->update([
                'order_crm_pre_pay'     => json_encode($prepare_pay_param,JSON_UNESCAPED_UNICODE),
                'order_crm_contents'    => json_encode($order_crm_contents_arr,JSON_UNESCAPED_UNICODE)
            ]);
        }
        
        //*********************************************交易结账***********************************************************
        if( empty($order_crm_contents_arr['serverBillIdPreConfirmPay']) ) {
            $prepare_pay_param = [
                'serverBillId'  => $serverBillId
            ];
            $result_prepare_confirm_pay = $client->vipUserOrderTradePay($prepare_pay_param);
            if( $result_prepare_confirm_pay['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"交易订单交易结账失败[{$result_prepare_confirm_pay['msg']}]，请核验!");
            }
            
            $order_crm_contents_arr['serverBillIdPreConfirmPay'] = true;
            $order_crm_contents_arr['sendGoodsPoints'] = (string)$result_prepare_confirm_pay['data']['billCent'];
            //更新数据表
            OrderSupplierAmountExtra::instance()->where('order_id',$order_supplier_id)->update([
                'order_crm_pay'         => json_encode($prepare_pay_param,JSON_UNESCAPED_UNICODE),
                'order_crm_contents'    => json_encode($order_crm_contents_arr,JSON_UNESCAPED_UNICODE)
            ]);
            $sendGoodsPoints = $order_crm_contents_arr['sendGoodsPoints'];
        } else {
            $sendGoodsPoints = $order_crm_contents_arr['sendGoodsPoints'];
        }
        
        return Normal::returnCode(Normal::SUC,"CRM交易处理完成",[
            'sendGoodsPoints'   => $sendGoodsPoints
        ]);
    }
    
    /**
     * 上传百大售后订单功能
     * 上传交易订单明细
     * @param array $binfo
     * @param array $orderRefund
     * @param array $orderRefundGoods
     * @param array $supplierOrder
     * @param array $order
     */
    public function uploadBdCrmOrderAfterSale(array $binfo,array $orderRefund,array $orderRefundGoods,array $supplierOrder,array $order)
    {
        $isNewMode = getIsNewBbcJavaMode();
        if( $isNewMode == 0 ) {
            return Normal::returnCode(Normal::SUC,"当前业务类型无须处理");
        }
        
        //原始订单数据ID
        $vipId                  = !empty($order['refund_extra_value']) && !empty($order['refund_extra_value']['vipId']) ? $order['refund_extra_value']['vipId'] : 0 ;
        $order_supplier_id      = $supplierOrder['id'];
        $order_trade_type       = $supplierOrder['order_trade_type'];
        $is_support_crm_upload  = $binfo['is_support_crm_upload'];
        $_extra_money           = OrderSupplierAmountExtra::instance()->info(['order_id'=>$order_supplier_id]);
        
        //判断定金和尾款是否一致
        $is_same_pay_mode = false;
        $deposit_pay_way  = '';
        if( $order_trade_type == OrderSupplier::order_trade_type_deposit && $_extra_money['deposit_mode'] != 1)
        {
            $_extra_money = OrderSupplierAmountExtra::instance()->info(['order_id'=>$order_supplier_id]);
            if( empty($_extra_money['deposit_pay_way']) ) {
                return Normal::returnCode(Normal::FAIL,"定金支付数据异常!");
            }
            $deposit_pay_way = $_extra_money['deposit_pay_way'];
            
            //判断定金和尾款支付方式是否一致
            if( $_extra_money['deposit_pay_way'] == $_extra_money['final_pay_way'] ) {
                $is_same_pay_mode = true;
            }
        }
        
        //需要获取原始的交易订单商品行ID
        if( $is_support_crm_upload == 1 ) 
        {
            $order_crm_arr = @json_decode($_extra_money['order_crm_contents'],true);
            if( empty($order_crm_arr['bd_crm_article_list']) ) {
                return Normal::returnCode(Normal::FAIL,"原始交易订单CRM商品行信息不能为空!");
            }
            
            $bd_crm_article_list_map = array_column($order_crm_arr['bd_crm_article_list'],null,'code');
        }else{
            $bd_crm_article_list_map = [];
        }
        
        //获取bd crm 交易中心config
        $config = OrderTradeBdCrmCenter::instance()->getBdCrmConfig();
        $client = new OrderTradeBdCrmCenter();
        
        
        //**************************上传交易商品接口****************************************
        //查询主商品档案三方skucode数据
        $skuCodes = array_column($orderRefundGoods,'skucode');
        $list = CommodityArchives::instance()->select(['SKUCode','SkuExtraCode'])->whereIn('SKUCode',$skuCodes)->get()->toArray();
        $listMap = array_column($list,null,'SKUCode');
        $crmArticleList = [];
        
        //结账的总金额
        $amount_total = $precard_money_total = $point_money_total = $qedk_money_total = $freight_total = $real_pay_money = $crm_discount_money_total = $deposit_discount_total = '0.00';
        
        //售后服务费
        $refund_service_fee_money = !empty($orderRefund['refund_service_fee_money']) ? $orderRefund['refund_service_fee_money'] : '0.00';
        
        //售后商品实际支付总金额
        $refund_goods_money = $orderRefund['refund_goods_money'];
        
        $has_refund_service_fee_money = '0.00';
        $count = count($orderRefundGoods);
        foreach ($orderRefundGoods as $index => $item)
        {
            $skucode                        = $item['skucode'];
            $skucode                        = !empty($listMap[$skucode]) && !empty($listMap[$skucode]['SkuExtraCode']) ? $listMap[$skucode]['SkuExtraCode'] : $skucode;
            $price                          = $item['price'];
            $buy_num                        = $item['buy_num'];
            $spec_num                       = $item['spec_num'];
            $refund_num                     = $item['refund_num'];
            $price_real_total_money         = $item['refund_goods_money'];
            $refund_discount_point_money    = $item['refund_discount_points_money'];
            $refund_discount_precard_money  = $item['refund_discount_precard_money'];
            $refund_discount_money          = $item['refund_discount_money'];
            $refund_delivery_money          = $item['refund_delivery_money'];
            $origin_goods_price             = bcmul($price,$buy_num,2);
            
            //售后服务费比例
            if( $index == $count - 1 )
            {
                $price_real_total_money         = bcsub($price_real_total_money,$has_refund_service_fee_money,2);
            }
            else
            {
                $scale_refund_service_fee       = bcdiv($price_real_total_money,$origin_goods_price,4);
                $scale_refund_service_fee_money = bcmul($refund_service_fee_money,$scale_refund_service_fee,2);
                $price_real_total_money         = bcsub($price_real_total_money,$scale_refund_service_fee_money,2);
                $has_refund_service_fee_money   = bcadd($has_refund_service_fee_money,$scale_refund_service_fee_money,2);
            }
            
            //定金分摊金额
            $refund_origin_discount_deposit_goods_money     = $item['refund_origin_discount_deposit_goods_money'];
            $refund_origin_discount_deposit_delivery_money  = $item['refund_origin_discount_deposit_delivery_money'];
            $refund_deposit_money                           = bcadd($refund_origin_discount_deposit_goods_money,$refund_origin_discount_deposit_delivery_money,2);
            
            $deposit_discount_total  = bcadd($deposit_discount_total,$refund_deposit_money,2);
            $deposit_discount_total  = bcadd($deposit_discount_total,$price_real_total_money,2);
            $deposit_discount_total  = bcadd($deposit_discount_total,$refund_delivery_money,2);
            
            //百大实际交易订单金额 = 实际支付+积分抵扣+预付卡+定金实际付款
            $discount_real_money    = bcadd($refund_discount_point_money,$refund_discount_precard_money,2);
            $amount                 = bcadd($price_real_total_money,$discount_real_money,2);
            $amount                 = bcadd($amount,$refund_deposit_money,2);
            
            //如果实际交易订单amount 为0，要设置为完全抵扣
            if( bccomp($amount,'0.00',2) == 0 )
            {
                $amount             = $refund_discount_money;
                $discountAmount     = '0.00';
                $qedk_money_total   = bcadd((string)$qedk_money_total,(string)$amount,2);
                $real_pay_money     = bcadd((string)$real_pay_money,(string)$discountAmount,2);
            }
            else
            {
                //三方实际支付金额
                $real_pay_money     = bcadd((string)$real_pay_money,(string)$price_real_total_money,2);
                //总优惠减去（预付卡+积分）
                $discountAmount     = bcsub($refund_discount_money,$discount_real_money,2);
            }
            $bd_crm_article_list_row = $bd_crm_article_list_map[$skucode] ?? [];
            // $originalInx = !empty($bd_crm_article_list_map[$skucode]) ? $bd_crm_article_list_map[$skucode]['inx'] : 0;
            $originalInx = $bd_crm_article_list_row['inx'] ?? 0;
            $crmArticleList[] = [
                'inx'               => $index,
                'originalInx'       => $originalInx,
                'code'              => $skucode,
                'saleDept'          => $config['saleDept'] ?? '',
                'quantity'          => $refund_num,
                'amount'            => '-'.$amount,
                'discountAmount'    => $discountAmount,
                'ContractCode'      => $config['contractNo'] ?? '',
                'noCent'            => 'N'
            ];
            
            $amount_total               = bcadd((string)$amount_total,(string)$amount,2);
            $precard_money_total        = bcadd((string)$precard_money_total,(string)$refund_discount_precard_money,2);
            $point_money_total          = bcadd((string)$point_money_total,(string)$refund_discount_point_money,2);
            $freight_total              = bcadd((string)$freight_total,(string)$refund_delivery_money,2);
            $crm_discount_money_total   = bcadd((string)$crm_discount_money_total,(string)$discountAmount,2);
        }
        
        //如果有运费的情况下单独在追加一个运费商品
        $real_pay_money = bcadd((string)$real_pay_money,(string)$freight_total,2);
        if( $freight_total > 0 )
        {
            $bd_crm_article_list_map_row = $bd_crm_article_list_map[$config['crm_trade_freight_goods_sku']] ?? [];
            // $originalInx = !empty($bd_crm_article_list_map[$config['crm_trade_freight_goods_sku']]) ? $bd_crm_article_list_map[$config['crm_trade_freight_goods_sku']]['inx'] : 0;
            $originalInx = $bd_crm_article_list_map_row['inx'] ?? 0;
            $crmArticleList[] = [
                'inx'               => count($orderRefundGoods),
                'originalInx'       => $originalInx,
                'code'              => $config['crm_trade_freight_goods_sku'] ?? '',
                'saleDept'          => $config['saleDept'] ?? '',
                'quantity'          => 1,
                'amount'            =>  '-'.$freight_total,
                'discountAmount'    => '0.00',
                'ContractCode'      => $config['contractNo'] ?? '',
                'noCent'            => 'N'
            ];
        }
        
        //类型 0销售 1 退货 2换货
        $type = $order['refundType'] == OrderRefundMessage::refund_type_refundchangegoods ? 2 : 1;
        $createOrderParam  = [
            'requestData'   => [
                'vipId'             => $vipId,
                'billId'            => 0,
                'orderNo'           => $orderRefund['refund_sn'],
                'originalOrderNo'   => $orderRefund['order_sn'],
                'type'              => $type,
                'orderCreateTime'   => !empty($order['payTime']) ? date("Y-m-d H:i:s",$order['payTime']) : date("Y-m-d H:i:s"),
                'articleList'       => $crmArticleList,
            ]
        ];
        
        //判断定金或者尾款的退回先后顺序
        //定金已退回金额
        //如果是预售订单非全款
        $refund_money_arr = [];
        $isPreSellNoneAllPayMoneyOrder = OrderPreSellService::instance()->isPreSellNoneAllPayMoneyOrder($supplierOrder,$_extra_money);
        if( $isPreSellNoneAllPayMoneyOrder ) 
        {
            $has_deposit_refund_money       = $_extra_money['deposit_refund_money'];
            $deposit_thirdparty_money       = $_extra_money['deposit_thirdparty_money'];
            $less_deposit_refund_money      = bcsub($deposit_thirdparty_money,$has_deposit_refund_money,2);
            
            //尾款已售后金额
            $has_final_refund_money         = $_extra_money['final_refund_money'];
            $final_thirdparty_money         = $_extra_money['final_thirdparty_money'];
            $less_final_refund_money        = bcsub($final_thirdparty_money,$has_final_refund_money,2);
            
            //处理扣款顺序
            if( bccomp($deposit_discount_total,$less_deposit_refund_money,2) <= 0 )  {//定金足够
                $refund_money_arr = [
                    'deposit_money'         => $deposit_discount_total,
                    'deposit_refund_money'  => bcadd($deposit_discount_total,$has_deposit_refund_money,2)
                ];
            } else if( $less_deposit_refund_money > 0 && bccomp($deposit_discount_total,$less_deposit_refund_money,2) > 0 ) {//定金不够,尾款补齐
                $diff_final_refund_money = bcsub($deposit_discount_total,$less_deposit_refund_money,2);
                $refund_money_arr = [
                    'deposit_money'         => $less_deposit_refund_money,
                    'deposit_refund_money'  => bcadd($less_deposit_refund_money,$has_deposit_refund_money,2),
                    'final_money'           => $diff_final_refund_money,
                    'final_refund_money'    => bcadd($has_final_refund_money, $diff_final_refund_money,2)
                ];
            } else if( bccomp($deposit_discount_total,$less_final_refund_money,2) <= 0 )  {//尾款足够
                $refund_money_arr = [
                    'final_money'           => $deposit_discount_total,
                    'final_refund_money'    => bcadd($has_final_refund_money,$deposit_discount_total,2)
                ];
            }
        }
        
        //判断CRM是否要上传
        if( $is_support_crm_upload == 1 ) {
            $result_create = $client->vipUserOrderTradeCreate($createOrderParam);
        } 
        else 
        {
            $result_create = Normal::returnCode(Normal::SUC,"当前无需上传CRM",[
                'needBuyCentMoney'  => '0.00',
                'needBuyCentMsg'    => ''
            ]);
        }
        
        if( $result_create['code'] == Normal::SUC ) 
        {
            $result_create['data']['bd_crm_amount']             = $real_pay_money;
            $result_create['data']['bd_crm_delivery_amount']    = $freight_total;
            $result_create['data']['bd_crm_discount_money']     = $crm_discount_money_total;
            $result_create['data']['bd_crm_precard_money']      = $precard_money_total;
            $result_create['data']['bd_crm_point_money']        = $point_money_total;
            $result_create['data']['bd_crm_qedk_money']         = $qedk_money_total;
            $result_create['data']['bd_crm_deposit_money']      = $deposit_discount_total;
            $result_create['data']['bd_crm_create']             = json_encode($createOrderParam,JSON_UNESCAPED_UNICODE);
            $result_create['data']['bd_crm_refund_money']       = $refund_money_arr;
        }
        return $result_create;
    }
    
    /**
     * 上传百大售后订单功能
     * 交易准备结账
     * 结账
     * @param array $binfo
     * @param array $orderRefund
     * @param array $supplierOrder
     * @param array $bd_crm_refund_money
     */
    public function uploadBdCrmOrderAfterPrepare(array $binfo,array $orderRefund,array $supplierOrder,array $bd_crm_refund_money)
    {
        $isNewMode = getIsNewBbcJavaMode();
        if( $isNewMode == 0 ) {
            return Normal::returnCode(Normal::SUC,"当前业务类型无须处理");
        }
    
        if( $binfo['is_full_support_after_sale'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"当前渠道数据类型无须处理");
        }

        if( $binfo['is_support_crm_upload'] == 0 ) {
            return Normal::returnCode(Normal::SUC,"当前渠道数据类型无须处理");
        }
        
        //退款订单ID
        $order_refund_id    = $orderRefund['id'];
        $order_id           = $orderRefund['sub_order_id'];
        $_extra_money       = OrderSupplierAmountExtra::instance()->info(['order_id'=>$order_id]);
        
        //如果没有付尾款不推送CRM
        if( $supplierOrder['order_trade_type'] == OrderSupplier::order_trade_type_deposit && $_extra_money['deposit_mode'] == 2 && bccomp((string)$_extra_money['final_money'],'0.00',2) == 0 )
        {
            return Normal::returnCode(Normal::SUC,"仅支付定金的情况下，不需要推送CRM接口");
        }
        
        if( empty($_extra_money['order_crm_contents']) ) {
            return Normal::returnCode(Normal::FAIL,"售后交易订单附加参数回写失败，请联系管理员进行核实处理");
        }
        
        //开始处理上传crm售后退款功能
        $order_crm_arr = @json_decode($_extra_money['order_crm_contents'],true);
        
        //获取bd crm 交易中心config
        $config = OrderTradeBdCrmCenter::instance()->getBdCrmConfig();
        $client = new OrderTradeBdCrmCenter();
        
        //*********************************************准备交易结账***********************************************************
        $refund_bd_crm_arr = @json_decode($orderRefund['refund_bd_crm_contents'],true);
        
        if( empty($refund_bd_crm_arr['serverBillid']) ) {
            return Normal::returnCode(Normal::FAIL,"售后交易订单附加参数serverBillid回写失败，请联系管理员进行核实处理");
        }
        
        //判断是否预售订单
        $is_same_pay_mode = $_extra_money['deposit_pay_way'] == $_extra_money['final_pay_way'];
        $deposit_pay_way = $_extra_money['deposit_pay_way'];
        if( empty($refund_bd_crm_arr['serverBillIdPrePay']) )
        {
            $serverBillId = $refund_bd_crm_arr['serverBillid'];
            $paymentList  = [];
            
            //预售订单,非全款模式
            $isPreSellNoneAllPayMoneyOrder = OrderPreSellService::instance()->isPreSellNoneAllPayMoneyOrder($supplierOrder,$_extra_money);
            if( $isPreSellNoneAllPayMoneyOrder ) 
            {
                //根据售后的金额来决定怎么退款到CRM
                //只有定金
                if( !empty($bd_crm_refund_money['deposit_money']) && 
                    bccomp((string)$bd_crm_refund_money['deposit_money'],'0.00',2) > 0 && 
                    empty($bd_crm_refund_money['final_money']) )
                {
                    $deposit_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$deposit_pay_way);
                    if( empty($deposit_pay_config) ) {
                        return Normal::returnCode(Normal::FAIL,"[只有定金模式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                    }
                
                    if( empty($deposit_pay_config['代码']) ) {
                        return Normal::returnCode(Normal::FAIL,"[只有定金模式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                    }
                    $paymentList[] = [
                        'PayTypeCode'   => $deposit_pay_config['代码'],
                        'PayMoney'      => "-".$bd_crm_refund_money['deposit_money'],
                        'IsCashCard'    => '0',
                        'BJ_TQ'         => '0'
                    ];
                }
                elseif ( 
                         !empty($bd_crm_refund_money['deposit_money']) &&
                         bccomp((string)$bd_crm_refund_money['deposit_money'],'0.00',2) > 0 &&
                         !empty($bd_crm_refund_money['final_money']) && 
                         bccomp((string)$bd_crm_refund_money['final_money'],'0.00',2) > 0
                    )
                {
                    $deposit_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$deposit_pay_way);
                    if( empty($deposit_pay_config) ) {
                        return Normal::returnCode(Normal::FAIL,"[有定金模式和尾款模式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                    }
                
                    if( empty($deposit_pay_config['代码']) ) {
                        return Normal::returnCode(Normal::FAIL,"[有定金模式和尾款模式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                    }
                
                    //支付方式相同，合并之后上传
                    if($is_same_pay_mode)
                    {
                        $_same_refund_money = bcadd($bd_crm_refund_money['deposit_money'],$bd_crm_refund_money['final_money'],2);
                        $paymentList[] = [
                            'PayTypeCode'   => $deposit_pay_config['代码'],
                            'PayMoney'      => "-".$_same_refund_money,
                            'IsCashCard'    => '0',
                            'BJ_TQ'         => '0'
                        ];
                    }
                    else
                    {
                
                        //定金
                        $deposit_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$deposit_pay_way);
                        if( empty($deposit_pay_config) ) {
                            return Normal::returnCode(Normal::FAIL,"[定金模式和尾款模式不同支付方式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                        }
                
                        if( empty($deposit_pay_config['代码']) ) {
                            return Normal::returnCode(Normal::FAIL,"云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                        }
                        $paymentList[] = [
                            'PayTypeCode'   => $deposit_pay_config['代码'],
                            'PayMoney'      => "-".$bd_crm_refund_money['deposit_money'],
                            'IsCashCard'    => '0',
                            'BJ_TQ'         => '0'
                        ];
                
                        //尾款
                        $final_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$_extra_money['final_pay_way']);
                        if( empty($final_pay_config) ) {
                            return Normal::returnCode(Normal::FAIL,"[定金模式和尾款模式不同支付方式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                        }
                
                        if( empty($final_pay_config['代码']) ) {
                            return Normal::returnCode(Normal::FAIL,"[定金模式和尾款模式不同支付方式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                        }
                
                        $paymentList[] = [
                            'PayTypeCode'   => $final_pay_config['代码'],
                            'PayMoney'      => "-".$bd_crm_refund_money['final_money'],
                            'IsCashCard'    => '0',
                            'BJ_TQ'         => '0'
                        ];
                    }
                } 
                elseif 
                ( 
                            empty($bd_crm_refund_money['deposit_money']) && 
                            !empty($bd_crm_refund_money['final_money']) && 
                            bccomp((string)$bd_crm_refund_money['final_money'],'0.00',2) > 0
                    ) 
                {
                    //尾款
                    $final_pay_config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('bd_crm_pay_'.$_extra_money['final_pay_way']);
                    if( empty($final_pay_config) ) {
                        return Normal::returnCode(Normal::FAIL,"[尾款模式支付方式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数未配置");
                    }
                
                    if( empty($final_pay_config['代码']) ) {
                        return Normal::returnCode(Normal::FAIL,"[尾款模式支付方式]云仓中台-系统管理-业务配置-百大支付方式-微信对应百大CRM参数代码未配置成功，不能为空!");
                    }
                
                    $paymentList[] = [
                        'PayTypeCode'   => $final_pay_config['代码'],
                        'PayMoney'      => "-".$bd_crm_refund_money['final_money'],
                        'IsCashCard'    => '0',
                        'BJ_TQ'         => '0'
                    ];
                }
            }
            else
            {
                //实际支付金额,普通正常订单
                $paymentList = [];
                if( !empty($refund_bd_crm_arr['bd_crm_amount']) && bccomp($refund_bd_crm_arr['bd_crm_amount'],'0.00',2) > 0)
                {
                    if( empty($order_crm_arr['OnlinePayTypeCode']) ) {
                        return Normal::returnCode(Normal::FAIL,"售后交易订单附加参数OnlinePayTypeCode回写失败，请联系管理员进行核实处理");
                    }
                
                    $paymentList[] = [
                        'PayTypeCode'   => $order_crm_arr['OnlinePayTypeCode'],
                        'PayMoney'      => "-".$refund_bd_crm_arr['bd_crm_amount'],
                        'IsCashCard'    => '0',
                        'BJ_TQ'         => '0'
                    ];
                }
            }
            
            //全额抵扣
            if( !empty($refund_bd_crm_arr['bd_crm_qedk_money']) && bccomp($refund_bd_crm_arr['bd_crm_qedk_money'],'0.00',2) > 0) 
            {
                if( empty($order_crm_arr['QedkPayTypeCode']) ) {
                    return Normal::returnCode(Normal::FAIL,"售后交易订单附加参数QedkPayTypeCode回写失败，请联系管理员进行核实处理");
                }
                
                $paymentList[] = [
                    'PayTypeCode'   => $order_crm_arr['QedkPayTypeCode'],
                    'PayMoney'      => "-".$refund_bd_crm_arr['bd_crm_qedk_money'],
                    'IsCashCard'    => '0',
                    'BJ_TQ'         => '0'
                ];
            }
            
            //预付卡
            if( !empty($refund_bd_crm_arr['bd_crm_precard_money']) && bccomp($refund_bd_crm_arr['bd_crm_precard_money'],'0.00',2) > 0) 
            {
                if( empty($order_crm_arr['PreCardPayTypeCode']) ) {
                    return Normal::returnCode(Normal::FAIL,"售后交易订单附加参数PreCardPayTypeCode回写失败，请联系管理员进行核实处理");
                }
                
                $paymentList[] = [
                    'PayTypeCode'   => $order_crm_arr['PreCardPayTypeCode'],
                    'PayMoney'      => "-".$refund_bd_crm_arr['bd_crm_precard_money'],
                    'IsCashCard'    => '1',
                    'BJ_TQ'         => '0'
                ];
            }
            
            //积分
            if( !empty($refund_bd_crm_arr['bd_crm_point_money']) && bccomp($refund_bd_crm_arr['bd_crm_point_money'],'0.00',2) > 0) 
            {
                if( empty($order_crm_arr['PointsPayTypeCode']) ) {
                    return Normal::returnCode(Normal::FAIL,"售后交易订单附加参数PointsPayTypeCode回写失败，请联系管理员进行核实处理");
                }
                
                $paymentList[] = [
                    'PayTypeCode'   => $order_crm_arr['PointsPayTypeCode'],
                    'PayMoney'      => "-".$refund_bd_crm_arr['bd_crm_point_money'],
                    'IsCashCard'    => '0',
                    'BJ_TQ'         => '0'
                ];
            }
            
            $prepare_pay_param =
            [
                'requestData'   => [
                    'serverBillId'  => $serverBillId,
                    'paymentList'   => $paymentList
                ]
            ];
            $result_prepare_pay = $client->vipUserOrderTradePreparePay($prepare_pay_param);
            if( $result_prepare_pay['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL, "CRM售后交易订单准备结账失败[{$result_prepare_pay['msg']}]，请核验!");
            }
            
            $refund_bd_crm_arr['serverBillIdPrePay']    = true;
            $refund_bd_crm_arr['OnlineDepositPayCode']  = !empty($deposit_pay_config['代码'])  ? $deposit_pay_config['代码'] : '';
            $refund_bd_crm_arr['OnlineFinalPayCode']  = !empty($final_pay_config['代码'])  ? $final_pay_config['代码'] : '';
            $refund_bd_crm_arr['PreCardPayTypeCode'] = !empty($order_crm_arr['PreCardPayTypeCode']) ? $order_crm_arr['PreCardPayTypeCode'] : '';
            $refund_bd_crm_arr['PointsPayTypeCode']  = !empty($order_crm_arr['PointsPayTypeCode'])  ? $order_crm_arr['PointsPayTypeCode'] : '';
            $refund_bd_crm_arr['QedkPayTypeCode']    = !empty($order_crm_arr['QedkPayTypeCode'])    ? $order_crm_arr['QedkPayTypeCode'] : '';
            
            //更新数据表
            OrderRefund::instance()->where('id',$order_refund_id)->update([
                'refund_bd_crm_pre_pay'     => json_encode($prepare_pay_param,JSON_UNESCAPED_UNICODE),
                'refund_bd_crm_contents'    => json_encode($refund_bd_crm_arr,JSON_UNESCAPED_UNICODE)
            ]);
        } 
        else
        {
            $serverBillId = $refund_bd_crm_arr['serverBillid'];
        }
        
        //*********************************************交易结账***********************************************************
        if( empty($refund_bd_crm_arr['serverBillIdPreConfirmPay']) ) 
        {
            $prepare_pay_param = [
                'serverBillId'  => $serverBillId
            ];
            $result_prepare_confirm_pay = $client->vipUserOrderTradePay($prepare_pay_param);
            if( $result_prepare_confirm_pay['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"CRM售后交易订单交易结账失败[{$result_prepare_confirm_pay['msg']}]，请核验!");
            }
            
            $refund_bd_crm_arr['serverBillIdPreConfirmPay'] = true;
            OrderRefund::instance()->where('id',$order_refund_id)->update([
                'refund_bd_crm_pay'         => json_encode($prepare_pay_param,JSON_UNESCAPED_UNICODE),
                'refund_bd_crm_contents'    => json_encode($refund_bd_crm_arr,JSON_UNESCAPED_UNICODE)
            ]);
        }
        return Normal::returnCode(Normal::SUC,"CRM售后交易处理完成");
    }
}